﻿#ifndef TRANSPORT_H
#define TRANSPORT_H

#include "platform.h"
#include <string>

enum class TResult {
    NoError = 0,
    DevNotFound,
    Access,
    ConnLost,
    IoError,
    TimedOut,
    OtherError
};


class Transport {
public:
    virtual ~Transport() = default;
    virtual TResult open() = 0;
    virtual TResult close() = 0;
    virtual TResult read(uint8_t* buf, int bytesToRead, long timeoutVal) = 0;
    virtual TResult write(const uint8_t* buf, int bytesToWrite, long timeoutVal) = 0;
    virtual void discardIoBuffers() = 0;
};


class SerialTransport : public Transport {
public:
    enum class Parity { None, Odd, Even };
    enum class StopBits { One, OnePointFive, Two };

public:
    SerialTransport(const char* portName,
        uint32_t baudRate = 9600,
        Parity parity = Parity::None,
        uint8_t dataBits = 8,
        StopBits stopBits = StopBits::One);
    ~SerialTransport();

    TResult open() override;
    TResult close() override;
    TResult read(uint8_t* buf, int bytesToRead, long timeoutVal) override;
    TResult write(const uint8_t* buf, int bytesToWrite, long timeoutVal) override;
    void discardIoBuffers() override;

protected:
    std::string m_portName;
    uint32_t m_baudRate;
    Parity m_parity;
    uint8_t m_dataBits;
    StopBits m_stopBits;

#ifdef PLATFORM_WINDOWS
    HANDLE m_fileHandle;
    OVERLAPPED m_ovRead;
    OVERLAPPED m_ovWrite;
#else
    int m_fileHandle;
#endif
};

#endif // TRANSPORT_H
